<!-- 试题修改 questionEdit -->
<template>
  <div class="content">
    <el-form class="page-form" :model="data" :rules="rules" ref="questionForm" size="medium" label-width="100px">

      <el-form-item label="题目：" prop="title">
        <el-input v-model="data.title" :rows="4" maxlength="100" show-word-limit type="textarea" class="page-form-item"
                  placeholder="请输入题目"></el-input>
      </el-form-item>

      <el-form-item label="题目类型：" prop="type">
        <el-select v-model="data.type" placeholder="请选择题目类型">
          <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="题目难度：" prop="difficult">
        <el-select v-model="data.difficult" placeholder="请选择题目难度">
          <el-option v-for="item in difficultList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属课程：" prop="courseId">
        <el-select v-model="data.courseId" placeholder="请选择所属课程">
          <el-option v-for="item in coruseList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="分值：" prop="maxScore">
        <el-input v-model="data.maxScore" placeholder="请输入分值"></el-input>
      </el-form-item>

      <el-form-item label="选项：" prop="answerOptions" v-if="data.type !== '3'">
        <el-input class="hidden-input" v-model="data.answerOptions" placeholder="请输入分值"></el-input>
        <div class="answer-list" v-for="v in answerOptions" :key="v.key">
          <div class="answer-label">选项{{v.key}}：</div>
          <div class="answer-input">
            <el-input :rows="1" type="textarea" v-model="v.value" maxlength="100" @change="onAnswerChangeInput"></el-input>
          </div>
          <div class="answer-right">
            <el-checkbox v-model="v.checked" @change="onAnswerChangeBox">正确答案</el-checkbox>
          </div>
        </div>
        <div class="answer-list">
          <div class="answer-label"></div>
          <el-button type="danger" :disabled="reduceDisabled" size="mini" @click="onOprOptions(2)">删除</el-button>
          <el-button type="primary" :disabled="addDisabled" size="mini" @click="onOprOptions(1)">添加</el-button>
        </div>
      </el-form-item>

      <el-form-item label="正确答案：" prop="rightAnswer" v-if="data.type === '3'">
        <el-input v-model="data.rightAnswer" :rows="3" type="textarea" maxlength="30" show-word-limit placeholder="请输入正确答案"></el-input>
        <div class="form-tips" style="right: 30px;">正确答案不得出现特殊符号、文字长度简短(尽量10字内,不超过30字)</div>
      </el-form-item>

      <el-form-item label="答案解析：" prop="rightReason">
        <el-input :rows="10" type="textarea" maxlength="500" show-word-limit v-model="data.rightReason" placeholder="请输入答案解析"></el-input>
      </el-form-item>

      <!-- <el-form-item label="试题图片：" prop="titleImg">
        <Upload v-model="data.titleImg" :limit="1" :fileLists="data.titleImg ? [data.titleImg]: []"></Upload>
      </el-form-item> -->

      <el-form-item>
        <el-button @click="handleResetForm('questionForm')">返 回</el-button>
        <el-button type="primary" :loading="btnLoading" @click="handleSubmitForm('questionForm')">保 存</el-button>
      </el-form-item>

    </el-form>
  </div>
</template>

<script>
import { GetQuestionDetail, GetCourseListWithoutPage, UpdateQuestion } from '@/api/train'
import { ExportList } from '@/utils'
import { QuestionsFormRules } from '@/utils/rules'
// import Upload from '@/components/Upload/edit'
export default {
  name: 'questionEdit',
  components: {},
  data () {
    return {
      select: 'select',
      letter: ['A', 'B', 'C', 'D', 'E', 'F'],
      selectLetter: [],
      // A-F
      answerOptions: [],
      detailId: '',
      data: {
        id: '',
        courseId: '',
        title: '',
        type: '',
        difficult: '',
        maxScore: '',
        rightAnswer: '',
        rightReason: '',
        belongToCoruse: '',
        answerOptions: '2',
        titleImg: ''
      },
      btnLoading: false,
      reduceDisabled: false,
      addDisabled: false,
      rules: QuestionsFormRules,
      coruseList: [],
      typeList: ExportList('questionTypeList'),
      difficultList: ExportList('difficultList')
    }
  },
  props: {},
  watch: {},
  computed: {},
  mounted () {
    this.selectLetter = this.letter.map(item => this.select + item)
    this.detailId = this.$route.query.id
    this.getDetail()
    this.getCoruse()
  },
  methods: {
    handleSubmitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) return

        if (this.data.type === '3') {
          let answerData = this.data
          this.addQuestionReq(answerData)
        } else {
          // 获取正确答案
          this.data.rightAnswer = this.getAnswerRight(2)
          let answerData = this.data
          if (!this.data.rightAnswer) {
            this.$message.warning('正确答案未勾选')
            return
          }
          // 单选
          if (answerData.type === '1') {
            if (this.getAnswerRight(1) > 1) {
              this.$message.warning('单选题正确答案只有一项！')
              return
            }
            this.addQuestionReq(answerData)
          }
          // 多选
          if (answerData.type === '2') {
            this.addQuestionReq(answerData)
          }
        }
      })
    },
    addQuestionReq (data) {
      this.btnLoading = true
      let params = data || {}
      // 存在空值 error
      const nullCount = this.getAnswerRight(3)
      if (nullCount > 0) {
        this.$message.warning('选项中的值不能为空！')
        return
      }
      this.answerOptions.forEach(e => {
        const key = this.select + e.key
        params[key] = e.value
      })
      // 找出 selectLetter 在 answerOptions中不存在的selectA/B/C/D/E/F
      let answerOptionsKey = this.answerOptions.map(e => this.select + e.key)
      const differences = this.getArrDifference(answerOptionsKey, this.selectLetter)
      differences.forEach(e => {
        params[e] = ''
      })
      this.btnLoading = true
      UpdateQuestion(params).then(res => {
        this.$message.success(res.message || '添加成功')
        setTimeout(() => {
          this.btnLoading = false
          this.$router.push({ name: 'train:questions' })
        }, 500)
      }).catch(e => {
        this.btnLoading = false
      })
    },
    handleResetForm (formName) {
      this.$router.go(-1)
    },
    // 获取答案
    getAnswerRight (val) {
      let count = 0
      let nullCount = 0
      let answer = ''
      this.answerOptions.forEach(e => {
        if (e.checked) {
          count++
          answer += e.key + ','
        }
        if (!e.value) {
          nullCount++
        }
      })
      // 数量
      if (val === 1) {
        return count
      }
      // 选项
      answer = answer.substring(0, answer.lastIndexOf(','))
      if (val === 2) {
        return answer
      }
      // 空值数
      if (val === 3) {
        return nullCount
      }
    },
    dealAnswerOptions (data) {
      const selectReg = this.select
      if (data) {
        const rightAnswer = data.rightAnswer.split(',')
        let arr = []
        this.letter.forEach(e => {
          const key = selectReg + e
          if (data[key]) {
            arr.push({ key: e, value: data[key], checked: rightAnswer.indexOf(e) > -1 })
          }
        })
        this.answerOptions = arr
      }
    },
    onOprOptions (val) {
      // A-F
      const len = this.answerOptions.length
      const letterLen = this.letter.length
      if (val === 1) {
        // + 一项
        if (len >= letterLen) {
          this.addDisabled = true
          this.$message.warning(`选项不得超过${letterLen}项`)
        } else {
          this.reduceDisabled = false
          this.answerOptions.push({ key: this.letter[len], value: '', checked: false })
        }
      } else {
        // - 一项
        if (len <= 2) {
          this.reduceDisabled = true
          this.$message.warning('选项不少于2项')
        } else {
          this.addDisabled = false
          this.answerOptions.splice(len - 1, 1)
        }
      }
    },
    onAnswerChangeInput () {
      this.data.answerOptions++
    },
    onAnswerChangeBox () {
      this.data.answerOptions++
    },
    getArrDifference (arr1, arr2) {
      return arr1.concat(arr2).filter(function (v, i, arr) {
        return arr.indexOf(v) === arr.lastIndexOf(v)
      })
    },
    getDetail () {
      let params = { id: this.detailId }
      GetQuestionDetail(params.id).then(res => {
        const data = res.data
        this.dealAnswerOptions(data)
        for (const key in this.data) {
          if (key === 'type' || key === 'difficult') {
            this.data[key] = data[key].toString()
          } else {
            this.data[key] = data[key]
          }
        }
        this.data.answerOptions = '2'
      }).catch(e => { })
    },
    getCoruse () {
      GetCourseListWithoutPage().then(res => {
        const data = res.data
        data.list.forEach(e => {
          e.value = e.id
          e.label = e.title
        })
        this.coruseList = data.list
      }).catch(e => {
        this.coruseList = []
      })
    }
  }
}

</script>
<style lang='scss' scoped>
</style>
